package com.ticket.sass.admin.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.reflect.TypeToken;
import com.ticket.sass.admin.business.ResourceBusiness;
import com.ticket.sass.admin.dto.PermResourceOutput;
import com.ticket.sass.admin.dto.RecursionResourceOutput;
import com.ticket.sass.admin.service.impl.ResourceServiceImpl;
import com.ticket.sass.admin.util.GsonUtil;
import com.ticket.sass.admin.util.ModelUtil;
import com.ticket.sass.common.entity.tenant.ResourceEntity;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2022-01-07 15:27
 */
@Service
@AllArgsConstructor
public class ResourceBusinessImpl implements ResourceBusiness {


    final ResourceServiceImpl service;
    final ModelUtil modelMap;
  
    @Override
    public List<RecursionResourceOutput> recursionList() {
        List<ResourceEntity> list = service.list(new QueryWrapper<ResourceEntity>().orderByAsc("sort"));
        return recursionTo(list, 0);
    }
    
    @Override
    public List<PermResourceOutput> permRecursionList() {
        List<ResourceEntity> list = service.list(new QueryWrapper<ResourceEntity>().orderByAsc("sort"));
        return permRecursionTo(list, 0);
    }
    
    
    private List<RecursionResourceOutput> recursionTo(List<ResourceEntity> list, Integer pid) {
        List<RecursionResourceOutput> outPuts = list.stream().filter(
            resource -> pid.equals(resource.getParentId())
        ).map(resource -> new RecursionResourceOutput(
            resource.getId(),
            resource.getName(),
            resource.getLevel(),
            resource.getParentId(),
            resource.getSort(),
            resource.getPerms(),
            resource.getRemark(),
            GsonUtil.getInstance().fromJson(resource.getData(), new TypeToken<Map<String, Object>>() {}.getType()))
        ).collect(Collectors.toList());
        outPuts.forEach(o -> o.setChildren(recursionTo(list, o.getId())));
        outPuts.sort(null);
        return outPuts;
    }
    
    private List<PermResourceOutput> permRecursionTo(List<ResourceEntity> list, Integer pid) {
        List<PermResourceOutput> outPuts = list.stream().filter(
            resource -> pid.equals(resource.getParentId())
        ).map(resource -> new PermResourceOutput(resource)).collect(Collectors.toList());
        outPuts.forEach(o -> o.setChildren(permRecursionTo(list, o.getId())));
        outPuts.sort(null);
        return outPuts;
    }
    
}
